package com.cci.zkweb.core.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;

import org.zkoss.zul.Listheader;

import com.cci.lib.ext.config.SharedConfig;

public class ZKFUtils {
	// Constants
	public static final String ANONYMOUS = "anonymous";
	public static final String DEFAULT_MIME_ICON = "default";
	public static final String PDF_MIME = "application/pdf";
	
	public static final String ROOT_FOLDER_CLASS = "tfolderRoot";
	public static final String FOLDER_CLASS = "tfolder";
	public static final String EMPTY_FOLDER_CLASS = "etfolder";
	public static final String CLOSED_FOLDER_ICON = "closedFolder";
	
	public static final String MIME_IMAGE_PATH = "/resources/images/mime/%s.png";
	public static final String ICON_IMAGE_PATH = "/resources/images/icons/%s.png";

	/**
	 * Get icon for mime type
	 * @param mime
	 * @return
	 */
	public static String getMimeTypeIcon(String mime) {
		return SharedConfig.getInstance().getValue("mime", mime, DEFAULT_MIME_ICON);
	}

	/**
	 * Add watermark to pdf stream
	 * @param pdfStream
	 * @param watermarkText
	 * @return
	 */
	public static OutputStream addWatermarkToPdfStream(InputStream pdfStream, String watermarkText) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		PDFWatermarkText tool = new PDFWatermarkText();
		tool.init();
		String[] params = {"drawText", watermarkText};
		tool.createWaterMarkPDF(params, pdfStream, out, false);
		
		return out;
	}
	
	/**
	 * Get file size in readable format
	 * @param size
	 * @return
	 */
	public static String readableFileSize(double size) {
	    if(size <= 0) return "0";
	    final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
	    int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
	    return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
	}
	
	/**
	 * Create a listheader
	 * @param label
	 * @param width
	 * @param align
	 * @param sort
	 * @return
	 */
	public static Listheader createListHeader(String label, String width, String align, String sort) {
		Listheader lh = new Listheader();
		if(label != null) lh.setLabel(label);
		if(width != null) lh.setWidth(width);
		if(align != null) lh.setAlign(align);
		if(sort != null) lh.setSort(sort);
		
		return lh;
	}
}
